package com.example.runningman.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.runningman.R;
import com.example.runningman.bean.Art;
import com.example.runningman.bean.Liked;
import com.example.runningman.bean.Remark;
import com.example.runningman.friend.FriendActivity;
import com.example.runningman.friend.SelfActivity;
import com.example.runningman.util.EmojiUtil;
import com.example.runningman.util.SPUtil;
import com.example.runningman.view.AutoLineFeedLayoutManager;
import com.example.runningman.view.QMAutoTestDialogBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Art_adapter extends RecyclerView.Adapter<Art_adapter.ViewHolder> {
    List<Art> mData;
    Activity mActivity;
    RequestOptions options;
    String useid;
    String remove = "0";

    boolean f = true;

    public Art_adapter(List<Art> data, Activity activity) {
        this.mData = data;

        this.mActivity = activity;
        useid = SPUtil.getInstance(mActivity).getString("useid");
        options = new RequestOptions()
                .placeholder(R.drawable.h_head)
                .override(80, 80)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v;

        v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_view, parent, false);


        // 实例化viewholder
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if(mData.get(position).getUserid().equals(SPUtil.getInstance(mActivity).getString("useid"))){
            holder.delete.setVisibility(View.VISIBLE);
        }else {
            holder.delete.setVisibility(View.GONE);
        }
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIDialog.MessageDialogBuilder(mActivity)
                        .setTitle("评论")
                        .setMessage("确定要删除吗？")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                postRequestRemove(mData.get(position).getArticleid()+"","");
                                mData.remove(position);

                                notifyDataSetChanged();
                                Toast.makeText(mActivity, "删除成功", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
        });
        holder.img_adapter = new Img_adapter(mData.get(position).getList_Img(), mActivity);
        holder.recyclerView_img.setLayoutManager(new GridLayoutManager(mActivity, 3));
        holder.recyclerView_img.setAdapter(holder.img_adapter);
        holder.remark_adapter = new Remark_adapter(mData.get(position).getList_Remarks(), mActivity);
        holder.layoutManager = new LinearLayoutManager(mActivity);
        holder.layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        holder.recyclerView_art.setLayoutManager(holder.layoutManager);
        holder.recyclerView_art.setAdapter(holder.remark_adapter);
        holder.like_adapter = new Like_adapter(mData.get(position).getList_Likes(), mActivity);
        holder.autoLineFeedLayoutManager = new AutoLineFeedLayoutManager();
        holder.recyclerView_like.setLayoutManager(holder.autoLineFeedLayoutManager);
        holder.recyclerView_like.setAdapter(holder.like_adapter);

        remove = "0";
        for (Liked like : mData.get(position).getList_Likes()) {
            if (useid.equals(like.getUserid())) {
                remove = "1";
                holder.like.setBackgroundResource(R.drawable.liked);
                break;
            }

        }
        holder.remark_adapter.setOnLongItemClickListener(new Remark_adapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View v, int position1) {

                if(mData.get(position).getList_Remarks().get(position1).getUserid().equals(SPUtil.getInstance(mActivity).getString("useid"))){
                    new QMUIDialog.MessageDialogBuilder(mActivity)
                            .setTitle("评论")
                            .setMessage("确定要删除吗？")
                            .addAction("取消", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                }
                            })
                            .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    postRequestRemove("",mData.get(position).getList_Remarks().get(position1).getRemarkid()+"");


                                    mData.get(position).getList_Remarks().remove(position1);
                                    holder.remark_adapter.refresh(mData.get(position).getList_Remarks());
                                    Toast.makeText(mActivity, "删除成功", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }


            }
        });
        holder.remark_adapter.setOnItemClickListener(new Remark_adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v,  int position1) {
                QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(mActivity);
                autoTestDialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {

                                Remark remark = new Remark();
                                remark.setUserid(SPUtil.getInstance(mActivity).getString("useid"));
                                remark.setNickname(SPUtil.getInstance(mActivity).getString("username"));
                                remark.setContent(autoTestDialogBuilder.getEditText().getText().toString());
                                remark.setArticleid(mData.get(position).getArticleid());
                                remark.setReplyid(mData.get(position).getList_Remarks().get(position1).getUserid());
                                remark.setReplyname(mData.get(position).getList_Remarks().get(position1).getNickname());
                                String s = gson.toJson(remark);
                                mData.get(position).getList_Remarks().add(remark);
                                holder.remark_adapter.refresh(mData.get(position).getList_Remarks());

                                postRequest(s);
                                Toast.makeText(mActivity, "你点了确定", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        });
                autoTestDialogBuilder.show();
                QMUIKeyboardHelper.showKeyboard(autoTestDialogBuilder.getEditText(), true);
            }
        });
        if (mData.get(position).getList_Likes().size() > 0) {
            holder.imageView.setVisibility(View.VISIBLE);
        }
        holder.mName.setText(mData.get(position).getUsername());
        try {
            holder.atica.setText(EmojiUtil.emojiRecovery(mData.get(position).getContent()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        holder.mName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, FriendActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("userid",mData.get(position).getUserid());
                intent.putExtras(bundle);
                mActivity.startActivity(intent);
            }
        });
        holder.mPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, FriendActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("userid",mData.get(position).getUserid());
                intent.putExtras(bundle);
                mActivity.startActivity(intent);
            }
        });
        holder.dk_time.setText(sdf.format(Long.parseLong(mData.get(position).getCreatetime())));
        Log.e("ssss", mData.get(position).getPhotoUrl() + "");
        Glide.with(mActivity).load(mData.get(position).getPhotoUrl()).apply(options).into(holder.mPic);//mData.get(position).getPhotoUrl()
        holder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("sss", holder.like.getBackground() + "");
                int count=0;
                if(mData.get(position).getList_Likes().size()==0){
                    f=true;
                    remove="0";
                }
                for (Liked like:mData.get(position).getList_Likes()) {


                    if(like.getUserid().equals(SPUtil.getInstance(mActivity).getString("useid"))){
                        f=false;
                        remove="1";
                        break;
                    }
                    count++;
                }

                if (f) {
                    holder.like.setBackgroundResource(R.drawable.liked);
                    Liked liked = new Liked();
                    liked.setArticleid(mData.get(position).getArticleid());
                    liked.setUserid(mData.get(position).getUserid());
                    liked.setUsername(SPUtil.getInstance(mActivity).getString("username"));
                    mData.get(position).getList_Likes().add(liked);
                    holder.like_adapter.refresh(mData.get(position).getList_Likes());
                } else {
                    holder.like.setBackgroundResource(R.drawable.like);
                    mData.get(position).getList_Likes().remove(count);
                    holder.like_adapter.refresh(mData.get(position).getList_Likes());
                    if (mData.get(position).getList_Likes().size() == 0) {
                        holder.imageView.setVisibility(View.GONE);
                    }
                    holder.imageView.setVisibility(View.GONE);
                }
                String s = postRequest(mData.get(position).getArticleid().toString(), useid, remove, SPUtil.getInstance(mActivity).getString("username"));
                Log.e("sss", s);
                notifyDataSetChanged();

            }
        });
        holder.art.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(mActivity);
                autoTestDialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {

                                Remark remark = new Remark();
                                remark.setUserid(SPUtil.getInstance(mActivity).getString("useid"));
                                remark.setNickname(SPUtil.getInstance(mActivity).getString("username"));
                                try {
                                    remark.setContent(EmojiUtil.emojiConvert(autoTestDialogBuilder.getEditText().getText().toString()));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                remark.setArticleid(mData.get(position).getArticleid());
                                String m = gson.toJson(remark);
                                postBaidu(autoTestDialogBuilder.getEditText().getText().toString(),m);



                                mData.get(position).getList_Remarks().add(remark);
                                holder.remark_adapter.refresh(mData.get(position).getList_Remarks());

                                    dialog.dismiss();

                            }
                        });
                autoTestDialogBuilder.show();
                QMUIKeyboardHelper.showKeyboard(autoTestDialogBuilder.getEditText(), true);
            }
        });


    }


    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public void refresh(List<Art> data) {
        this.mData = data;
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView mName;
        TextView atica;
        ImageView mPic;
        TextView dk_time;
        Button like;
        Button art;
        RecyclerView recyclerView_img;
        RecyclerView recyclerView_art;
        RecyclerView recyclerView_like;
        Img_adapter img_adapter;
        Like_adapter like_adapter;
        Remark_adapter remark_adapter;
        LinearLayoutManager layoutManager;
        Button delete;
        AutoLineFeedLayoutManager autoLineFeedLayoutManager;

        public ViewHolder(View itemView) {
            super(itemView);
            mName = itemView.findViewById(R.id.user);
            atica = itemView.findViewById(R.id.atica);

            dk_time = itemView.findViewById(R.id.time_re);
            mPic = itemView.findViewById(R.id.pic);
            like = itemView.findViewById(R.id.like);
            delete = itemView.findViewById(R.id.delete);
            art = itemView.findViewById(R.id.art);
            imageView = itemView.findViewById(R.id.ddds);
            recyclerView_art = itemView.findViewById(R.id.recy_art);
            recyclerView_img = itemView.findViewById(R.id.recy_img);
            recyclerView_like = itemView.findViewById(R.id.recy_like);

        }
    }

    private static Gson gson = new Gson();


    final OkHttpClient client = new OkHttpClient();


    /**
     * post请求后台
     */
    String s = "0";

    private String postRequest(String articleId, String userId, String remove, String name) {
        //建立请求表单，添加上传服务器的参数

        RequestBody formBody = new FormBody.Builder()
                .add("remove", remove)
                .add("name", name)
                .add("articleId", articleId)
                .add("userId", userId)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addLike?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        s = response.body().string();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return s;
    }

    private void postRequest(String remark) {
        //建立请求表单，添加上传服务器的参数

        RequestBody formBody = new FormBody.Builder()
                .add("remark", remark)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addremark?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui


                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postRequestRemove(String articleId,String remarkid) {
        //建立请求表单，添加上传服务器的参数

        RequestBody formBody = new FormBody.Builder()
                .add("remarkid", remarkid)
                .add("articleId", articleId)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/deleteRemark?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui


                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postBaidu(String text,String m) {
        //建立请求表单，添加上传服务器的参数

        RequestBody formBody = new FormBody.Builder()
                .add("access_token", "24.7ec06635d6a1fa0ec5b001fef0cf1d76.2592000.1591175866.282335-19718698")
                .add("text", text)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String s =response.body().string();
                        String conclusion;
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            conclusion= jsonObject.getString("conclusion");
                            if(conclusion.equals("合规") ){
                                postRequest(m);
                            }



                        } catch (JSONException e) {
                            e.printStackTrace();
                        }





                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }




}